package com.sky.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.sky.constant.StatusConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    //根据开始和结束日期活动日期列表
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate dateIndex = begin;//日期指针

        while (!dateIndex.isAfter(end)) {
            dateList.add(dateIndex);
            dateIndex = dateIndex.plusDays(1);//指针后移1天
        }

        log.info("得到的日期集合:{}", dateList);
        return dateList;
    }

    //营业额统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.接收参数处理成日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //2.声明返回结果变量
        List turnoverList = new ArrayList<>(); //营业额的集合
        //3.凑数据(调用mapper查询统计结果)
        for (LocalDate date : dateList) {
            double amount = reportMapper.sumOrderAmountByStatusAndDate(5, date);
            turnoverList.add(amount);
        }
        System.out.println(CollectionUtil.join(dateList, ",")); //日期列表
        System.out.println(CollectionUtil.join(turnoverList, ",")); //营业额列表
        //4.封装vo返回结果
        return TurnoverReportVO.builder()
                .dateList(CollectionUtil.join(dateList, ","))
                .turnoverList(CollectionUtil.join(turnoverList, ","))
                .build();
    }

    //用户统计
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.接收参数处理成日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //2.声明返回结果变量
        List newUserList = new ArrayList<>();//每天新增用户
        List totalUserList = new ArrayList<>();//每天累计新增用户

        //3.凑数据(调用mapper查询统计结果)
        int total = 0; //存储到某天为止累加新增数量
        for (LocalDate date : dateList) {
            //查询每天新增用户数
            int num = reportMapper.countUserByDate(date);
            newUserList.add(num);
            total = total + num;
            totalUserList.add(total);
        }

        //4.封装vo返回结果
        return UserReportVO.builder()
                .newUserList(CollectionUtil.join(newUserList, ","))
                .dateList(CollectionUtil.join(dateList, ","))
                .totalUserList(CollectionUtil.join(totalUserList, ","))
                .build();
    }

    //订单统计
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.接收参数处理成日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //2.声明返回结果变量
        List orderCountList = new ArrayList<>();//订单数列表
        int totalOrderCount = 0;//订单总数
        List validOrderCountList = new ArrayList<>();//有效订单数列表
        int validOrderCount = 0;//有效订单数
        double orderCompletionRate = 0; //订单完成率==有效订单数/订单总数*100%
        //3.凑数据(调用mapper查询统计结果)
        for (LocalDate date : dateList) {
            //3-1每天的订单数
            int orderCount = reportMapper.countOrderByStatusAndDate(null, date);
            //3-2放到订单数列表
            orderCountList.add(orderCount);
            totalOrderCount += orderCount;
            //3-3每天有效订单
            int validCount = reportMapper.countOrderByStatusAndDate(5, date);
            //3-4放到有效订单数列表
            validOrderCountList.add(validCount);
            validOrderCount += validCount;
        }
        if (totalOrderCount > 0 && validOrderCount > 0) {
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
            orderCompletionRate = NumberUtil.round(orderCompletionRate, 4).doubleValue();//保留小数点
        }
        //4.封装vo返回结果
        return OrderReportVO.builder()
                .dateList(CollectionUtil.join(dateList, ","))
                .orderCountList(CollectionUtil.join(orderCountList, ","))
                .validOrderCountList(CollectionUtil.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    //查询销量排名top10接口
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.声明变量返回
        List<String> nameList = new ArrayList();
        List<Integer> numberList = new ArrayList();

        //2.凑数据(调用mapper查询统计结果)
        List<GoodsSalesDTO> list = reportMapper.countSalesRankTop10(begin, end);
        if (CollectionUtil.isNotEmpty(list)) {
            for (GoodsSalesDTO dto : list) {
                //2-1获取商品名称
                nameList.add(dto.getName());
                //2-2获取商品销量
                numberList.add(dto.getNumber());
            }
        }
        //3.封装vo返回结果
        return SalesTop10ReportVO.builder()
                .nameList(CollectionUtil.join(nameList, ","))
                .numberList(CollectionUtil.join(numberList, ","))
                .build();
    }

    //今日运营数据
    @Override
    public BusinessDataVO businessData(LocalDate today) {
        //1.声明返回变量
        Integer newUsersCount = 0;//新增用户数
        double orderCompletionRate = 0;//订单完成率
        double turnover = 0;//营业额
        double unitPrice = 0;//平均客单价
        Integer validOrderCount = 0;//有效订单数
        //2.凑数据(调用mapper查询统计结果)
        //2-1营业额
        turnover = reportMapper.sumOrderAmountByStatusAndDate(5, today);
        //2-2有效订单数
        validOrderCount = reportMapper.countOrderByStatusAndDate(5, today);
        //2-3新增用户数
        newUsersCount = reportMapper.countUserByDate(today);
        //2-4平均客单价
        if (turnover > 0 && validOrderCount > 0) {
            unitPrice = turnover / validOrderCount;
            unitPrice = NumberUtil.round(unitPrice, 4).doubleValue();
        }
        //2-5订单完成率
        int totalOrderCount = reportMapper.countOrderByStatusAndDate(null, today);
        if (totalOrderCount > 0 && validOrderCount > 0) {
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
            orderCompletionRate = NumberUtil.round(orderCompletionRate, 4).doubleValue();
        }
        //3.封装vo返回结果
        return BusinessDataVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount)
                .newUsers(newUsersCount)
                .build();
    }

    //查询订单管理数据
    @Override
    public OrderOverViewVO overviewOrders(LocalDate today) {
        //1.声明返回变量
        Integer waitingOrders = 0;//待接单数
        Integer deliveredOrders = 0;//待派送数
        Integer completedOrders = 0;//完成订单数
        Integer cancelledOrders = 0;//取消订单数
        Integer allOrders = 0;//全部订单
        //2.凑数据(调用mapper查询统计结果)
        //2-1待接单数
        waitingOrders = reportMapper.countOrderByStatusAndDate(2, today);
        //2-2待派送数
        deliveredOrders = reportMapper.countOrderByStatusAndDate(3, today);
        //2-3完成订单数
        completedOrders = reportMapper.countOrderByStatusAndDate(5, today);
        //2-4取消订单数
        cancelledOrders = reportMapper.countOrderByStatusAndDate(6, today);
        //2-5全部订单数
        allOrders = reportMapper.countOrderByStatusAndDate(null, today);
        //3.封装vo返回结果
        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    //菜品总览（作业）//套餐总览（作业）
    @Override
    public DishOverViewVO countStatus(String temp) {
        //停售的数量
        Integer MinimumQuantity = 0;//起售的数量
        Integer TheNumberOfDiscontinued = 0;//停售数量
        if (temp.equals("dish")) {
            //菜品
            MinimumQuantity = reportMapper.countDishByStatus(temp, StatusConstant.ENABLE);
            TheNumberOfDiscontinued = reportMapper.countDishByStatus(temp, StatusConstant.DISABLE);
        } else {
            //套餐
            MinimumQuantity = reportMapper.countDishByStatus(temp, StatusConstant.ENABLE);
            TheNumberOfDiscontinued = reportMapper.countDishByStatus(temp, StatusConstant.DISABLE);
        }
        //封装vo返回结果
        return DishOverViewVO.builder()
                .sold(MinimumQuantity)
                .discontinued(TheNumberOfDiscontinued)
                .build();
    }

}
